import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tender_flutter/constant/app_config.dart';
import 'package:tender_flutter/constant/app_constant.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/utils/utils.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';

import 'api/api_person.dart';
import 'model/consumption_entity.dart';
import 'model/pay_params.dart';

/// 消费记录
class ConsumptionPage extends StatefulWidget {
  @override
  _ConsumptionPageState createState() => _ConsumptionPageState();
}

class _ConsumptionPageState extends State<ConsumptionPage> {
  /// 刷新组件
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  Future<ApiResponse<ConsumptionEntity>> _listFuture;

  LoadState _loadState = LoadState.State_Loading;

  int page = AppConfig.page;

  int pageCount = AppConfig.pageCount;

  /// 列表数据
  List<ConsumptionList> _dataLists = [];

  ///刷新数据
  Future _refresh() async {
    if (_refreshController.isRefresh) {
      page = 1;
    }
    if (_refreshController.isLoading) {
      page += 1;
    }

    setState(() {
      _listFuture = _getData();
    });
  }

  /// 获取数据
  Future<ApiResponse<ConsumptionEntity>> _getData() async {
    var response = await ApiPerson.getConsumptionList<ConsumptionEntity>(
      page: page,
      pageCount: pageCount,
    );
    return response;
  }

  FutureBuilder<ApiResponse<ConsumptionEntity>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _listFuture,
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<ConsumptionEntity>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              ConsumptionEntity entity = snapshot.data.result;
              print("测试" + snapshot.data.toString());
              if (snapshot.data.status == Status.SUCCESS) {
                List temps = entity.xList == null ? [] : entity.xList;
                page == AppConfig.page
                    ? _dataLists = temps
                    : _dataLists += temps;
                if (_dataLists.isEmpty) {
                  _loadState = LoadState.State_Empty;
                } else {
                  _loadState = LoadState.State_Success;
                }
              } else {
                _loadState = LoadState.State_Error;
              }
            } else if (snapshot.hasError) {
              _loadState = LoadState.State_Error;
            }

            /// 结束刷新，处理分页
            if (_dataLists.length % AppConfig.pageCount != 0) {
              _refreshController.loadNoData();
            } else {
              if (_refreshController.isLoading) {
                _refreshController.loadComplete();
              }
            }
            if (_refreshController.isRefresh) {
              _refreshController.refreshCompleted();
            }
          }

          return LoadStateLayout(
            bgColor: ThemeColors.colorWhite,
            state: _loadState,
            successWidget: _initList(),
          );
        });
  }

  @override
  void initState() {
    super.initState();
    _listFuture = _getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeColors.colorWhite,
      appBar: _initAppBar(),
      body: _buildFutureBuilder(),
    );
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(context, Text("购买记录", style: FonStyle.navTextStyle()),
        backgroundColor: ThemeColors.colorWhite,
        actions: <Widget>[
          InkWell(
              onTap: () {
                if (_dataLists.isNotEmpty) {
                  LRouter.navigatorCtx(context).push(Routes.applyInvoicePage,
                      arguments: ApplyInvoicePageArguments(
                          consumptionBean: _dataLists[0]));
                } else {
                  ToastUtils.show("没有可开具发票的消费信息");
                }
              },
              child: IntrinsicHeight(
                child: Container(
                    alignment: Alignment.center,
                    padding: EdgeInsets.only(
                        left: ScreenAdapter.width(15),
                        right: ScreenAdapter.width(30)),
                    child: Text("申请发票",
                        style: TextStyle(color: ThemeColors.colorType4))),
              )),
        ]);
  }

  /// 主体内容列表
  Widget _initList() {
    return SmartRefresher(
        controller: _refreshController,
        enablePullUp: true,
        enablePullDown: true,
        onRefresh: _refresh,
        onLoading: _refresh,
        child: ListView.separated(
          itemCount: _dataLists.length,
          itemBuilder: (BuildContext context, int index) {
            ConsumptionList model = _dataLists[index];
            return _getCell(
                model: model,
                onTap: () {
                  if (model.isPayed) {
                    LRouter.navigatorCtx(context).push(Routes.applyInvoicePage,
                        arguments:
                            ApplyInvoicePageArguments(consumptionBean: model));
                  } else {
                    PayParams params = PayParams();
                    params.goodsDes = model.mark;
                    params.goodsId = int.parse(model.id);
                    params.goodsPrice = double.parse(model.pay);
                    params.orderType = AppConstant.PAY_ORDER_WAIT;
                    LRouter.navigatorCtx(context).push(Routes.paymentPage,
                        arguments: PaymentPageArguments(payParams: params));
                  }
                });
          },
          separatorBuilder: (BuildContext context, int index) {
            return Divider(color: ThemeColors.colorType49);
          },
        ));
  }

  /// Item列表
  Widget _getCell({ConsumptionList model, GestureTapCallback onTap}) {
    return InkWell(
      onTap: onTap,
      child: Container(
        margin: EdgeInsets.symmetric(
            horizontal: ScreenAdapter.width(30),
            vertical: ScreenAdapter.height(15)),
        child: Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(
                    "订单编号：${isEmpty(model.orderNo) ? "-" : model.orderNo}",
                    style: TextStyle(
                        color: ThemeColors.colorType14,
                        fontSize: ScreenAdapter.sp(26),
                        fontWeight: FontWeight.w500),
                  ),
                ],
              ),
              SizedBox(height: ScreenAdapter.height(20)),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(
                    !isEmpty(model.expireDate)
                        ? "${model.createDate} - ${model.expireDate}"
                        : model.createDate,
                    style: TextStyle(
                        color: ThemeColors.colorType26,
                        fontSize: ScreenAdapter.sp(26)),
                  ),
                  Text(
                    // DateTime.fromMillisecondsSinceEpoch(int.parse(model.createDate))
                    //     .toString(),
                    model.isPayed ? "已支付" : "未支付",
                    style: TextStyle(
                        color: ThemeColors.colorType16,
                        fontSize: ScreenAdapter.sp(26),
                        fontWeight: FontWeight.bold),
                  ),
                ],
              ),
              SizedBox(height: ScreenAdapter.height(20)),
              Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                Text(model.mark ?? "-",
                    textAlign: TextAlign.left,
                    maxLines: 2,
                    softWrap: true,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: ThemeColors.colorType1,
                      fontWeight: FontWeight.w500,
                      fontSize: ScreenAdapter.sp(28),
                    )),
                Text(
                  "¥${model.pay}",
                  style: TextStyle(
                      color: ThemeColors.colorType16,
                      fontSize: ScreenAdapter.sp(28),
                      fontWeight: FontWeight.w500),
                ),
              ]),
            ],
          ),
        ),
      ),
    );
  }
}
